<template>
  <div ref="mainCon" class="container">
    <div class="mainCon">
      <div class="toolbar searchInputWidth" style="padding-bottom: 0">
        <el-form :inline="true" :model="filterField" ref="searchConditions">
          <el-col :lg="8" :xl="6">
            <el-form-item label="承保机构名称" class="row-padding-bottom">
              <el-input
                placeholder="请输入承保机构名称"
                v-model="filterField.name"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="所属保函类型" class="row-padding-bottom">
              <el-select
                v-model="filterField.type"
                filterable
                placeholder="请选择"
                clearable
                :popper-append-to-body="false"
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-form-item label="">
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <div style="margin-bottom: 24px">
          <el-button
            class="commonBut saveBtn funComBut"
            icon="icon iconfont icontianjia"
            @click="toAdd()"
          >
            <span class="opetareText">添加</span>
          </el-button>
        </div>
        <el-table
          ref="tableBox1"
          border
          :max-height="tableHeight"
          @selection-change="handleSelectionChange"
          :data="tableList"
          v-loading="loading"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          style="border: 1px solid #dfe6ec"
        >
          <el-table-column label="承保机构名称" width="230">
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.name"
                :columnName="'name'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            prop="typeDesc"
            label="所属保函类型"
            align="center"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            prop="status"
            label="启用/禁用状态"
            align="center"
            :formatter="formatTd"
            width="130"
          >
            <template slot-scope="scope">
              <span class="redColor" v-if="scope.row.status == 'OFF'"
                >禁用</span
              >
              <span class="successColor" v-else-if="scope.row.status == 'ON'"
                >启用</span
              >
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="insInsurersUserVOS"
            label="保险业务员账号"
            width="230"
            :formatter="formatTd"
          >
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.insInsurersUserVOSHtml"
                :columnName="'insInsurersUserVOSHtml'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left" fixed="right" width="160">
            <template slot-scope="scope">
              <el-link type="primary" @click="toDetail(scope.$index, scope.row)"
                >查看详情</el-link
              >
              <el-link type="primary" @click="toEdit(scope.$index, scope.row)"
                >修改</el-link
              >
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关信息"></emptyTable>
          </div>
        </el-table>
        <Pagination
          ref="pagination"
          @getpageNo="getpageNo"
          @getpageSize="getpageSize"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
        ></Pagination>
      </div>
    </div>
    <!-- 弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="type == 'add' ? '添加承保机构' : '修改承保机构'"
      :visible.sync="formVisible"
      width="750px"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="125px"
        class="ruleForm"
      >
        <el-form-item label="承保机构名称" prop="organizationName">
          <el-input
            class="elInput"
            placeholder="请输入"
            v-model="ruleForm.organizationName"
            clearable
            maxlength="80"
            show-word-limit
            :disabled="type == 'edit' ? true : false"
          ></el-input>
        </el-form-item>

        <el-form-item label="所属保函类型" prop="type">
          <el-select
            v-model="ruleForm.type"
            placeholder="请选择"
            style="width: 375px"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.code"
              :label="item.name"
              :value="item.code"
              multiple
            >
            </el-option>
          </el-select>
        </el-form-item>

        <div
          class="informationBox"
          v-for="(item, index) of ruleForm.informationList"
          :key="index"
        >
          <el-form-item
            :prop="'informationList.' + index + '.name'"
            class="information"
            :rules="rules.name"
            :label="index == 0 ? '投保资料' : ''"
          >
            <el-input
              class="elInput"
              placeholder="请输入"
              v-model="item.name"
              clearable
              show-word-limit
              maxlength="80"
            ></el-input>
            <span :class="index == 0 ? 'firstSpan' : ''">
              <el-checkbox
                v-model="item.choice"
                true-label="YES"
                false-label="NO"
                >必传</el-checkbox
              >
              <i class="delIcon" v-if="index > 0" @click="delInformation(index)"
                >删除</i
              >
            </span>
          </el-form-item>
        </div>

        <el-row @click.native="addInformation" class="addLevel">
          <span style="font-size: 25px">+</span>
          <!-- <span style="position: relative; top: -4px">添加等级</span> -->
        </el-row>
        <el-form-item label="简介" prop="description">
          <el-input
            type="textarea"
            v-model="ruleForm.description"
            autocomplete="off"
            placeholder="请输入"
            maxlength="300"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="启用/禁用状态" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio label="ON">启用</el-radio>
            <el-radio label="OFF">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="保险业务员账号" prop="insInsurersUsersList">
          <el-select
            v-model="ruleForm.insInsurersUsersList"
            filterable
            multiple
            placeholder="请选择"
            multiple-limit="5"
            style="width: 375px"
          >
            <el-option
              v-for="item in allInsurerOptions"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel()" class="cancel">取 消</el-button>
        <el-button type="primary" @click="toSave('ruleForm')" class="save"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import scrollTable from '@/mixin/scrollTable.js'
export default {
  name: 'guaranteeConfig',
  mixins: [scrollTable],
  data() {
    return {
      //表格数据
      tableList: [],
      requestUrl: 'api-d/insconfiginsurers/list',
      //搜索条件
      filterField: {
        name: '', //名称
        type: '', //保函类型
      },
      pageSize: 20,
      pageNo: 1,
      typeOptions: [],
      //弹窗正则
      rules: {
        organizationName: [
          { required: true, message: '请输入承保机构', trigger: 'blur' },
        ],
        type: [
          { required: true, message: '请选择保函类型', trigger: 'change' },
        ],
        name: [
          {
            required: true,
            message: '请填写投保资料，并标记是否必传',
            trigger: 'blur',
          },
        ],
        description: [
          { required: true, message: '请输入简介', trigger: 'change' },
        ],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        insInsurersUsersList: [
          { required: true, message: '请选择保险业务员', trigger: 'change' },
        ],
      },
      formVisible: false,
      //弹窗添加数据
      ruleForm: {
        organizationName: '', //承保机构
        type: '', //保函类型
        description: '', // 简介
        status: '', //状态
        informationList: [
          {
            name: '',
            choice: '',
          },
        ],
        insInsurersUsersList: [],
      },
      allInsurerOptions: [],
      type: 'add',
    }
  },

  created() {
    this.getSelectData()
    this.getInsInsurersUsers()
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
  },
  mounted() {},
  activated() {
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
    })
  },
  methods: {
    getpageSize(val) {
      this.pageSize = val
    },
    getpageNo(val) {
      this.pageNo = val
    },
    getTableList(data) {
      this.tableList = data
      this.loading = false

      this.tableList.forEach((item) => {
        var newArr = []
        item.insInsurersUserVOS.forEach((each) => {
          newArr.push(each.nickname)
        })
        item.insInsurersUserVOSHtml = newArr.join('、')
      })
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    // 搜索
    searchList() {
      this.pageSize = 20
      this.pageNo = 1
      this.$refs.pagination.getTableListData()
    },
    getSelectData() {
      this.axios({
        method: 'post',
        url: 'api-bs/base/dicitem/findbytype',
        data: {
          type: 'DEPOSIT_INSURE_TYPE',
        },
      })
        .then((response) => {
          this.typeOptions = response.data.result
        })
        .catch((response) => {})
    },
    getInsInsurersUsers() {
      this.axios({
        method: 'post',
        url: 'api-u/users/findAllInsurer',
      })
        .then((response) => {
          this.allInsurerOptions = response.data
        })
        .catch((response) => {})
    },

    toAdd() {
      this.type = 'add'
      this.formVisible = true

      this.$nextTick(function () {
        this.$refs.ruleForm.resetFields()
        this.ruleForm.organizationName = ''
        this.ruleForm.id = ''
        this.ruleForm.name = ''
        this.ruleForm.status = ''
        this.ruleForm.type = ''
        this.ruleForm.description = ''
        this.ruleForm.informationList = [
          {
            name: '',
            choice: '',
          },
        ]
        this.ruleForm.insInsurersUsersList = []
      })
    },
    addInformation() {
      if (this.ruleForm.informationList.length == 10) {
        this.$message({
          message: '最多添加 10项',
          type: 'warning',
        })
        return
      }
      let addObj = {}
      addObj.name = ''
      addObj.choice = ''
      this.ruleForm.informationList.push(addObj)
    },
    delInformation(index) {
      if (this.ruleForm.informationList.length == 1) {
        return
      } else {
        this.ruleForm.informationList.splice(index, 1)
      }
    },
    toSave(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.save(formName)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    save(formName) {
      var insInsurersUsers = []
      this.ruleForm.insInsurersUsersList.forEach((item, index) => {
        insInsurersUsers.push({ userId: item })
      })
      this.ruleForm.informationList.forEach((item, index) => {
        if (!item.choice) {
          item.choice = 'NO'
        }
      })
      var insItemJson = JSON.stringify(this.ruleForm.informationList)
      // this.ruleForm.insInsurersUsers = JSON.stringify(insInsurersUsers);
      // this.ruleForm.insItemJson = insItemJson;
      // this.ruleForm.name = this.ruleForm.organizationName;
      var data = {
        name: this.ruleForm.organizationName,
        id: this.ruleForm.id,
        insItemJson: insItemJson,
        insInsurersUsers: JSON.stringify(insInsurersUsers),
        status: this.ruleForm.status,
        type: this.ruleForm.type,
        description: this.ruleForm.description,
      }
      // delete item1.name;
      var url = 'api-d/insconfiginsurers/add'
      if (this.type == 'edit') {
        url = 'api-d/insconfiginsurers/edit'
      }
      this.axios({
        method: 'post',
        url: url,
        data: data,
      }).then((response) => {
        if (!response.data.hasError) {
          this.formVisible = false
          this.$message({
            message: this.type == 'edit' ? '修改成功' : '添加成功',
            type: 'success',
          })
          this.$nextTick(function () {
            this.$refs.pagination.getTableListData()
          })
          this.$refs[formName].resetFields()
        } else {
          this.$message({
            message: response.data.errorMsg,
            type: 'error',
          })
        }
      })
      // .catch(response => {});
    },
    async toEdit(index, row) {
      await this.getDetail(row.id)
      this.type = 'edit'
      this.formVisible = true
    },
    cancel() {
      this.formVisible = false
      this.$refs['ruleForm'].resetFields()
    },
    //获取详情
    getDetail(id) {
      return this.axios({
        method: 'post',
        url: 'api-d/insconfiginsurers/detail',
        data: { id: id },
      })
        .then((response) => {
          if (!response.data.hasError) {
            var row = response.data.result
            this.ruleForm.organizationName = row.name
            this.ruleForm.id = row.id
            this.ruleForm.name = row.name
            this.ruleForm.status = row.status
            this.ruleForm.type = row.type
            this.ruleForm.description = row.description
            this.ruleForm.insInsurersUsersList = []
            if (row.insInsurersUserVOS) {
              row.insInsurersUserVOS.forEach((item, index) => {
                this.ruleForm.insInsurersUsersList.push(item.userId)
              })
            }
            this.ruleForm.informationList = []
            if (row.insItemVOS) {
              row.insItemVOS.forEach((item, index) => {
                this.ruleForm.informationList.push({
                  name: item.name || '',
                  choice: item.choice || 'NO',
                })
              })
            }
          } else {
            this.$message({
              message: response.data.errorMsg,
              type: 'error',
            })
          }
        })
        .catch((error) => {})
    },
    // 查看详情
    toDetail(index, row) {
      this.$router.push({
        path: '/home/newInsurance/guaranteeConfigDetail',
        name: 'guaranteeConfigDetail',
        query: {
          id: row.id,
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/newInsurance/insuranceConfig',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
  },
}
</script>

<style scoped lang="less">
.ruleForm {
  width: 500px;
}

.addLevel {
  height: 32px;
  text-align: center;
  line-height: 30px;
  font-size: 14px;
  color: #a3a3a3;
  border: 1px dashed #dee5f4;
  margin-left: 125px;
  margin-bottom: 22px;
}
.addLevel:hover {
  cursor: pointer;
  color: #409eff;
  border-color: #409eff;
}

.informationBox {
  position: relative;
  margin-bottom: 22px;
  span {
    position: absolute;
    top: 0;
    right: -130px;
    i {
      font-style: normal;
      cursor: pointer;
      margin-left: 24px;
    }
  }
  .firstSpan {
    right: -73px;
  }
}

.informationBox:last-of-type {
  margin-bottom: 0;
}

.elInput /deep/ .el-input__inner {
  padding-right: 68px;
}
</style>
